<script lang="ts" setup>
import { addComment, getComment, type commentForm } from '@/api/course';
import { useStudentStore } from '@/stores/student';
import { ElMessage } from 'element-plus';
import moment from 'moment';
import { onMounted, ref } from 'vue';
const props = defineProps(["cid"])
const commentList = ref<commentForm[]>([])
const getAllComment = async () => {
  let res = await getComment(props.cid);
  commentList.value = res.data;
}
const newComment = ref<commentForm>({
  studentUsername: useStudentStore().studentInfo.username,
  courseId: props.cid
})
const dialogVisible = ref(false)
const handleComment = async () => {
  newComment.value.createTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
  let res = await addComment(newComment.value)
  ElMessage.success(res.data)
  dialogVisible.value = false
  window.location.reload();
}

onMounted(() => {
  getAllComment();
})
</script>
<template>
  <div class="home-comment">
    <div class="title">用户留言
      <el-button style="float: right;" type="primary" @click="dialogVisible = true">添加留言</el-button>
    </div>
    <div class="comment-list">
      <div v-for="(item) in commentList" v-bind:key="item.id" class="comment-item">
        <div class="user-content">
          <el-image class="avator" :src="item.avatar"></el-image>
          <span class="user">{{ item.studentUsername }}</span>
        </div>
        <div class="comment">{{ item.content }}</div>
        <div class="create-time">{{ item.createTime }}</div>
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" title="给课程添加留言吧" width="500" draggable>
    <el-form>
      <el-form-item label=" 留言">
        <el-input v-model="newComment.content" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleComment">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.home-comment {
  background: #ffffff;

  .title {
    font-size: 18px;
    color: #666;
    font-weight: bold;
    padding: 10px;
    border-bottom: 1px solid #eeeeee;
  }

  .comment-list {
    padding: 10px;

    .comment-item {
      padding: 10px;
      border-bottom: 1px solid #eeeeee;

      .user-content {
        display: flex;

        .user {
          font-size: 18px;
          color: #666;
          font-weight: bold;
          line-height: 50px;
          margin-left: 10px;
        }

        .avator {
          width: 50px;
          height: 50px;
          border-radius: 50%;
        }
      }

      .comment {
        margin-top: 10px;
        font-size: 14px;
        color: #888888;
      }

      .create-time {
        margin-top: 15px;
        font-size: 14px;
        color: #888888;
      }
    }
  }
}
</style>
